// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: leon

#pragma once

#include <rapidjson/document.h>
#include <rapidjson/rapidjson.h>

#include <string>

#include "coin/proto/coin_market_enums.pb.h"
#include "coin2/base/conversion.h"
#include "coin2/exchange/base/feed/update.h"
#include "coin2/exchange/base/feed_util/book_builder.h"
#include "coin2/exchange/base/feed_util/trade.h"

namespace impl {
using coin2::exchange::base::market::ExchangeType;
using coin2::exchange::base::market::MarketType;

class PancakeswapFeedUpdateParser {
 public:
  static void ParseBbo(BookBuilder* book_builder_,
                       const rapidjson::Document& document,
                       int64_t timestamp) {
    auto tx = book_builder_->NewTransaction(timestamp);
    tx.Clear();

    {
      auto ask0 = document["ask0"].GetArray();
      double price = ask0[0].GetDouble();
      double size = ask0[1].GetDouble();
      tx.UpdateAsk(price, size);
    }

    {
      auto bid0 = document["bid0"].GetArray();
      double price = bid0[0].GetDouble();
      double size = bid0[1].GetDouble();
      tx.UpdateBid(price, size);
    }
  }

  static void ParseTrade(
      const rapidjson::Value& trade_json,
      Trade* trade, int64_t timestamp) {
    trade->price = trade_json["price"].GetDouble();
    trade->fill_qty = trade_json["qty"].GetDouble();
    trade->side = ParseTradeSide(trade_json["side"].GetString());
    trade->timestamp = timestamp;
  }

  static coin2::exchange::feed::TradeSide ParseTradeSide(
      const std::string& side) {
    if (side == "B") {
      return coin2::exchange::feed::TRADE_BUY_SIDE;
    } else if (side == "S") {
      return coin2::exchange::feed::TRADE_SELL_SIDE;
    } else {
      throw std::runtime_error("[Pancakeswap] unknown side: " + side);
    }
  }
};
}  // namespace impl

using impl::PancakeswapFeedUpdateParser;
